package com.health.system.springSecurity;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.web.FilterInvocation;


import com.health.system.javacommon.util.StringTool;
import com.health.system.model.system.User;
import com.health.system.service.system.UserManager;

/**
 * 对session失效进行跳转处理
 * 
 */
public class SessionTimeOutFilter implements Filter {

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String logonUserName = LogonUser.getUserName();
		String requestUrl = SpringSecurityConstant.LOGON_URL;
		String j_systemName = request.getParameter("j_systemName");
		String username = request.getParameter("j_username");
		//System.out.println("#################################### "+username);
		String sessionId =httpRequest.getRequestedSessionId();
		boolean idValid =httpRequest.isRequestedSessionIdValid();
		String requestURI =httpRequest.getRequestURI();
		HttpSession session = httpRequest.getSession(false); 
		
		if (!idValid) {//未登录 session超时失效处理
			System.out.println("==========================");
			RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(requestUrl);
			if (null != dispatcher) {
				dispatcher.forward(request, response);
				if (null != requestURI&& !requestURI.equals(SpringSecurityConstant.REQUEST_LOGON_URL)) {
					httpRequest.getSession().setAttribute(SpringSecurityConstant.TIMEOUT_MARK, true);//超时时给session中setAttribute该属性为true
				}
			}
			return;
			
		} else if (idValid&& null == httpRequest.getSession().getAttribute(SpringSecurityConstant.TIMEOUT_MARK)) {
		
			String code = request.getParameter(SpringSecurityConstant.CODE);
			
			//System.out.println("-------------	String code = request.getParameter(SpringSecurityConstant.CODE);------------"+code);
			
			String beforeCode = (String) httpRequest.getSession().getAttribute(SpringSecurityConstant.SESSION_CODE);
			String requestName = getUserName(request.getParameter(SpringSecurityConstant.LOGON_USERNAME));
			//SPRING_SECURITY_LAST_NAME
			if (null != requestName && !"".equals(requestName)) {
				httpRequest.getSession().setAttribute(SpringSecurityConstant.SPRING_SECURITY_LAST_NAME,requestName);//存入用户名
				httpRequest.getSession().setAttribute("systemName",j_systemName);//
			}
			if (null != code && !"".equals(code) && null != beforeCode&& !"".equals(beforeCode)) {
				if (!code.equalsIgnoreCase(beforeCode)) {
					requestUrl = SpringSecurityConstant.VALIDE_ERROR_URL;
					RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(requestUrl);
					if (dispatcher != null) {
						dispatcher.forward(request, response);
					}
					return;
				}
			}
			if (null != username&&username.length()>0 ) { 
				UserManager userManager = (UserManager)com.health.system.javacommon.util.SpringContextUtil.getBean("userManager");
				User userInfo = (User)userManager.getUserByName(username);
				if(null==userInfo){
				    requestUrl = SpringSecurityConstant.ORGAN_ERROR_URL;
					RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(requestUrl);
					if (dispatcher != null) {
						dispatcher.forward(request, response);
					}
					return;
				}
			}
			
			FilterInvocation filterInvocation = new FilterInvocation(request,response, chain);
			filterInvocation.getChain().doFilter(filterInvocation.getRequest(),filterInvocation.getResponse());
		} else {
			//System.out.println("&&&&&&&&&&&&&&&&&&&&&");
			if (null == logonUserName || "".equals(logonUserName)) {
				logonUserName =getUserName( request.getParameter(SpringSecurityConstant.LOGON_USERNAME));
				if (null == logonUserName || "".equals(logonUserName)) {
					if (requestURI.equals(SpringSecurityConstant.REQUEST_LOGON_URL)|| requestURI.equals(SpringSecurityConstant.REQUEST_LOGON)) {
						requestUrl = SpringSecurityConstant.LOGON_URL;
					}
					
					if (requestURI.contains(SpringSecurityConstant.CODE_JSP)) {
						FilterInvocation filterInvocation = new FilterInvocation(request, response, chain);
						filterInvocation.getChain().doFilter(filterInvocation.getRequest(),filterInvocation.getResponse());
					} else if (!requestURI.endsWith(SpringSecurityConstant.NOT_JSP)) {
						if (session!=null&&!"true".equals(session.getAttribute("isLogin"))&&requestURI.endsWith(".do")) {
							RequestDispatcher dispatcher = httpRequest.getRequestDispatcher("/login.jsp");
							if (dispatcher != null) {
								dispatcher.forward(request, response);
							}
						}else{
							FilterInvocation filterInvocation = new FilterInvocation(request, response, chain);
							filterInvocation.getChain().doFilter(filterInvocation.getRequest(),filterInvocation.getResponse());
						}
					} else {
						RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(requestUrl);
						if (dispatcher != null) {
							dispatcher.forward(request, response);
						}
						return;
					}
				} else {
					//System.out.println("/////////////////////////////");
					//校验页面验证码是否正确
					logonUserName = getUserName(logonUserName);
					httpRequest.getSession().setAttribute(SpringSecurityConstant.SPRING_SECURITY_LAST_NAME,logonUserName);
					httpRequest.getSession().setAttribute(SpringSecurityConstant.TIMEOUT_MARK, null);
					String code = request.getParameter(SpringSecurityConstant.CODE);
					String beforeCode = (String) httpRequest.getSession().getAttribute(SpringSecurityConstant.SESSION_CODE);
					if (null != code && !"".equals(code) && null != beforeCode&& !"".equals(beforeCode)) {
						if (!code.equalsIgnoreCase(beforeCode)) {
							requestUrl = SpringSecurityConstant.VALIDE_ERROR_URL;
							RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(requestUrl);
							if (dispatcher != null) {
								dispatcher.forward(request, response);
							}
							return;
						}
					}
					
				
					FilterInvocation filterInvocation = new FilterInvocation(request, response, chain);
					filterInvocation.getChain().doFilter(filterInvocation.getRequest(),filterInvocation.getResponse());
				}
				
			}
		}
	}
	
	/**
	 * 分割 前台传来的 登录名称
	 * 如果是登录名+,+机构代码则分割字符串，取第一节返回
	 * @param name
	 * @return
	 */
	private String getUserName(String name){
		String[] temp = StringTool.SplitString(name, ",");
		String j_username ="";
		String j_organCode = "";
		if(null!=temp&&temp.length>=2){
			 j_username = temp[0];
			 j_organCode = temp[1]; 
			 return j_username;
		}else{
			return name;
		}
	}
	public void init(FilterConfig arg0) throws ServletException {
	}

}
